﻿Imports System.Data.SqlClient
Imports System.IO
Imports System.Xml
Imports System.Data
Imports Microsoft.Win32
Imports Microsoft.ReportingServices
Imports Microsoft.Reporting.WinForms

Public Class FrmCostoProducto

    Private oDataAdapter As SqlDataAdapter
    Public carrito2 As New DataTable("Detalle")
    Private dr As DataRow
    Public totalpres As Integer

    Dim controller As New Class_RC_Controller.rc_CostoActividad
    Private _codProducto As Integer = 0

    Public Property codProducto() As Integer
        Get
            Return _codProducto
        End Get
        Set(ByVal value As Integer)
            _codProducto = value
            txtcodProd.Text = value.ToString().PadLeft(4, "0")
        End Set
    End Property

    Private Sub FrmCostoProducto_Disposed(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Disposed

    End Sub
    Private Sub FrmCostoProducto_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        llenarcboactividad()
        llenarcbotipoemp()
        habilitar()
        limpiar()
        'txtcodProd.Text = FrmProductos.codProducto
        CargarDetalles()
    End Sub
    Private Sub llenarcboactividad()
        Dim dsactividad As DataTable
        dsactividad = controller.get_Actividades(oiml.dbConn)
        With Me.cmbactividad
            .DataSource = dsactividad
            .DisplayMember = "DescActividad"
            .ValueMember = "CodActividad"
        End With
    End Sub
    Private Sub llenarcbotipoemp()
        Dim dstipoemp As DataTable
        dstipoemp = controller.get_tipo_Empleado(oiml.dbConn)
        With Me.cmbtipoemp
            .DataSource = dstipoemp
            .DisplayMember = "DescTipoEmp"
            .ValueMember = "CodTipoEmp"
        End With

    End Sub
    Private Sub Promedio(ByVal id As Integer)
        Dim valpromedio As Decimal
        'oDataAdapter = New SqlDataAdapter("SELECT AVG(SalHora) AS Promedio FROM dbo.CATEGORIAS WHERE CodTipoEmp=" & id, cn)
        'Dim odataset As DataSet
        'odataset = New DataSet
        'cn.Open()

        'oDataAdapter.Fill(odataset, "dbo.CATEGORIAS")
        'Dim oDataRow As DataRow
        'oDataRow = odataset.Tables("dbo.CATEGORIAS").Rows(0)
        'valpromedio = oDataRow("Promedio")
        'txtcosto.Text = FormatNumber(valpromedio, 0, , , TriState.True)

        'cn.Close()
        Dim dspromedio As DataTable
        dspromedio = controller.get_promedio(oiml.dbConn, id)
        valpromedio = dspromedio.Rows(0)("promedio")
        txtcosto.Text = FormatNumber(valpromedio, 0, , , TriState.True)

    End Sub


    Private Sub habilitar()
        '****Inhabilitar los textbox
        txtcodProd.Enabled = False
        txtcantemp.Enabled = True
        txtcosto.Enabled = False
        txtcostoact.Enabled = False
        txthoras.Enabled = True
        txttotalmano.Enabled = False
        '****Inhabilitar los combobox
        cmbactividad.Enabled = True
        cmbtipoemp.Enabled = True
        '****inhabilitar los botones
        btnagregar.Enabled = True
        btneliminar.Enabled = True
        btncancelar.Enabled = True
        txtcodProd.BackColor = System.Drawing.Color.White
        txtcantemp.BackColor = System.Drawing.Color.White
        txtcosto.BackColor = System.Drawing.Color.White
        txtcostoact.BackColor = System.Drawing.Color.White
        txthoras.BackColor = System.Drawing.Color.White
        txttotalmano.BackColor = System.Drawing.Color.White
        cmbactividad.BackColor = System.Drawing.Color.White
        cmbtipoemp.BackColor = System.Drawing.Color.White
        '****Inhabilitar los botones para agregar una nueva nota
        btnaceptar.Enabled = True
    End Sub


    Private Sub limpiar()
        'txtcodProd.Text = ""
        txtcantemp.Text = ""
        txtcosto.Text = ""
        txtcostoact.Text = ""
        txthoras.Text = ""
        'txttotalmano.Text = ""
        cmbactividad.Text = ""
        cmbtipoemp.Text = ""
    End Sub

    Private Sub cmbtipoemp_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmbtipoemp.SelectedIndexChanged
        If (IsNumeric(cmbtipoemp.SelectedValue)) Then
            Dim id As Integer
            id = cmbtipoemp.SelectedValue
            Promedio(id)
        End If
        
    End Sub

    Private Sub CargarDetalles()
        Dim codactividad As Integer
        codactividad = cmbactividad.SelectedValue
        If codProducto > 0 Then
            txtcodProd.Text = codProducto
            Dim dt As New DataTable
            dt = controller.get_CostoActividad_All(oiml.dbConn, codProducto)
            If Not dt Is Nothing Then
                dgvdetalle.AutoGenerateColumns = False
                dgvdetalle.DataSource = dt
                totales()
            End If

        End If
    End Sub
    Private Sub totales()
        Dim i As Integer
        For i = 0 To dgvdetalle.Rows.Count - 1
            totalpres += CDec(dgvdetalle.Rows(i).Cells(8).Value)
        Next
        txttotalmano.Text = FormatNumber(totalpres, 0, , , TriState.True)
    End Sub
    Private Sub btnagregar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnagregar.Click
        Try

            If ValidarDetalleCampos() Then
                Exit Sub
            End If

            codProducto = controller.Insert_CostoActividad(oiml.dbConn, cmbactividad.SelectedValue, txtcodProd.Text, cmbtipoemp.SelectedValue,
                                                    txtcantemp.Text, txthoras.Text, Decimal.Parse(txtcosto.Text), Decimal.Parse(txtcostoact.Text))
            If codProducto = 0 Then
                MessageBox.Show("Error: " & controller.MessageError.Message, "Productos", MessageBoxButtons.OK, MessageBoxIcon.Error)
                Exit Sub
            End If
        Catch ex As Exception
            MsgBox(ex.Message)

        End Try
        totalpres = 0
        CargarDetalles()
        dgvdetalle.Refresh()
        cmbactividad.Focus()
        limpiar()
    End Sub
    Private Function ValidarDetalleCampos() As Boolean

        Dim controlCampos As Boolean = False

        If Not IsNumeric(txtcantemp.Text) Then
            ErrorProvider.SetError(txtcantemp, "Campo numerico, Cantidad")
            controlCampos = True
        Else
            ErrorProvider.SetError(txtcantemp, "")
        End If

        If Not IsNumeric(txthoras.Text) Then
            ErrorProvider.SetError(txthoras, "Campo numerico, Precio")
            controlCampos = True
        Else
            ErrorProvider.SetError(txthoras, "")
        End If
        Return controlCampos

    End Function

    Private Sub CalTotal()
        Try
            Dim a, b, c, d As Integer
            a = Val(txtcantemp.Text)
            b = Val(Me.txthoras.Text)
            c = (Me.txtcosto.Text)
            d = (a * b) * c
            txtcostoact.Text = FormatNumber(d, 0, , , TriState.True)
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub

    Private Sub txthoras_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txthoras.KeyPress
        If e.KeyChar = ChrW(Keys.Enter) Then
            e.Handled = True
            SendKeys.Send("{TAB}")
        End If
        If e.KeyChar.ToString() = "." Then
            e.KeyChar = ","
        End If
    End Sub



    Private Sub txthoras_LostFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles txthoras.LostFocus
        CalTotal()
    End Sub




    Private Sub txtcantemp_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtcantemp.KeyPress
        If e.KeyChar = ChrW(Keys.Enter) Then
            e.Handled = True
            SendKeys.Send("{TAB}")
        End If

    End Sub

    Private Sub btnaceptar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnaceptar.Click
        FrmProductos.totalCosto = totalpres
        Me.DialogResult = Windows.Forms.DialogResult.OK
        Me.Close()

    End Sub


    Private Sub cmbactividad_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles cmbactividad.KeyPress
        If e.KeyChar = ChrW(Keys.Enter) Then
            e.Handled = True
            SendKeys.Send("{TAB}")
        End If
    End Sub
    Private Sub cmbtipoemp_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles cmbtipoemp.KeyPress
        If e.KeyChar = ChrW(Keys.Enter) Then
            e.Handled = True
            SendKeys.Send("{TAB}")
        End If
    End Sub

    Private Sub btncancelar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btncancelar.Click
        Me.Close()
    End Sub

    Private Sub btneliminar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btneliminar.Click
        Try
            If dgvdetalle.SelectedRows.Count > 0 Then
                Dim codactividad As Integer
                codactividad = dgvdetalle.SelectedRows(0).Cells(0).Value

                If codactividad > 0 And MessageBox.Show("Desea eliminar esta Actividad del Proceso de Produccion?", "ACTIVIDAD", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then

                    If controller.Delete_CostoActividad(oiml.dbConn, codProducto, codactividad) Then
                        totalpres = 0
                        CargarDetalles()
                    Else
                        MessageBox.Show("Error: " & controller.MessageError.Message, "Actividad", MessageBoxButtons.OK, MessageBoxIcon.Error)

                    End If

                End If

            End If

        Catch ex As Exception
            MsgBox(ex.Message)

        End Try
    End Sub
End Class